<?php
	class Durak extends CI_Controller{
		function __construct(){
			parent::__construct();
		}
		
		function index(){
			$this->setSession();
			$this->playAgain();
			
		}
		
		function play(){
			$data['currentPlayer'] = $this->session->userdata('currentPlayer');
			$data['nextPlayer'] = $this->getNextPlayer($data['currentPlayer']);
			$data['hand'] = $this->getHand($data['currentPlayer']);
			$data['opponentHand'] = $this->getHand($data['nextPlayer']);
			$data['status'] = $this->session->userdata('status');
			$data['deckCount'] = count($this->session->userdata('deck'));
			$data['workSpace'] = $this->session->userdata('workSpace');
			$data['trump'] = $this->session->userdata('trump');
			$data['attackCount'] = $this->session->userdata('attackCount');
			$data['option'] = $this->session->userdata('option');
			$data['fScore'] = $this->session->userdata('fScore');
			$data['sScore'] = $this->session->userdata('sScore');
			$data['shuffle'] = $this->getShuffle($data['currentPlayer']);
			$data['opponentShuffle'] = $this->getShuffle($data['nextPlayer']);
			$data['alert'] = $this->session->userdata('alert');
			$data['parts'] = array('parts/info', 'parts/workspace', 'parts/player');
			
			$this->load->view('templates/header', $data);
			$this->load->view('durak_view', $data);
		}
		
		function initializePlay($win=false, $player=1){
			$this->reset();
			$this->shuffle();
			$this->setOrder($win, $player);
			
			redirect('letsplaydurak');
		}
		
		function shuffle(){
			$fHand = $this->session->userdata('firstHand');
			$sHand = $this->session->userdata('secondHand');
			$fCount = 0;
			$sCount = 0;
			
			for($i=0; $i<6; $i++){												// Compares each card in the hand to other cards on hand
				for($j=0; $j<6; $j++){
					if($fHand[$i]['suit']==$fHand[$j]['suit'])					// if card's suit matches another card's suit
						$fCount++;												// increase count
					if($sHand[$i]['suit']==$sHand[$j]['suit'])				
						$sCount++;
				}																// if count is less than 5 by the end of comparison
					if($fCount<5)												// reset count
						$fCount = 0;
					if($sCount<5)
						$sCount = 0;
			}
			if($fCount>=5)
				$this->session->set_userdata('fShuffle', 1);
			if($sCount>=5)
				$this->session->set_userdata('sShuffle', 1);
		}
		
		function reset(){
			$this->setDeck();
			$this->session->set_userdata('workSpace', []);
			$this->session->set_userdata('firstHand', []);
			$this->session->set_userdata('secondHand', []);
			$this->session->set_userdata('attackCount', 0);
			$this->session->set_userdata('fShuffle', 0);
			$this->session->set_userdata('sShuffle', 0);
			$firstHand = $this->session->userdata('firstHand');
			$secondHand = $this->session->userdata('secondHand');
			$this->setHand(1,$firstHand);
			$this->setHand(2,$secondHand);
			$this->setTrump();
		}
		
		function sortHand($player, $hand, $index){
			//var_dump($hand);
			$temp = [];
			array_unshift($temp, $hand[$index]);
			unset($hand[$index]);
			foreach($hand as $h):
			//var_dump($temp);
			array_push($temp, $h);
			endforeach;
		// exit;
			$this->setHand($player, $temp, 6);
		}
		
//=============================================================================================================================================================
// SET FUNCTIONS
//=============================================================================================================================================================
		function setShuffle($player, $onOff){
			if($player==1)
				$this->session->set_userdata('fShuffle', $onOff);
			else
				$this->session->set_userdata('sShuffle', $onOff);
		}
		
		function setOrder($hasWinner, $player){
			$trump = $this->session->userdata('trump')['suit'];
			$fHand = $this->session->userdata('firstHand');
			$sHand = $this->session->userdata('secondHand');
			$fTemp = [];
			$sTemp = [];
			$fTrumpFound = false;
			$sTrumpFound = false;
			
			if($hasWinner){															// Checks if there's a previous winner
				$this->setPlayer($player);											// If there is, he attacks first
				$this->session->set_userdata('alert', 'Player '.$player.' attacks first!');
			}else{																	// If not
				for($i=0;$i<6; $i++){												// Checks the player's hands if there's a trump card
					if($fHand[$i]['suit']==$trump){									// If first player has trump card
						$this->sortHand(1, $fHand, $i);

						if($fTrumpFound){											// If there's a previous trump card
							if($fTemp['value']>$fHand[$i]['value'])							// compares the previous to current
								$fTemp = $fHand[$i];						// sets the temp to the lower value
						}else{														// If there's no previous trump card	
							$fTemp = $fHand[$i];							// sets the temp to current value
							$fTrumpFound = true;
						}
						$fHand = $this->session->userdata('firstHand');
					}
					if($sHand[$i]['suit']==$trump){									// same as above, only this time, player 2's hand
						$this->sortHand(2, $sHand, $i);

						if($sTrumpFound){
							if($sTemp['value']>$sHand[$i]['value'])
								$sTemp = $sHand[$i];
						}else{
							$sTemp = $sHand[$i];
							$sTrumpFound = true;
						}
					}
					$sHand = $this->session->userdata('secondHand');
				}
				
				if($fTrumpFound && $sTrumpFound){									// if trump is found on both sides
					if($fTemp<$sTemp){												// compare the values
						$this->setPlayer(1);										// if fTemp is lower, player 1 attacks first
						$this->session->set_userdata('alert', 'Player 1 has the lowest trump card, Player 1 attacks first!');
					}else{															// otherwise, player 2 attacks first
						$this->setPlayer(2);
						$this->session->set_userdata('alert', 'Player 2 has the lowest trump card, Player 2 attacks first!');
					}
				}elseif(!$fTrumpFound && !$sTrumpFound){								// if no trump is found, player 1 attacks first
					$this->setPlayer(1);
					$this->session->set_userdata('alert', 'No trump was present on either hands, Player 1 attacks first!');
				}elseif($fTrumpFound && !$sTrumpFound){								// if trump is only found on player 1's hand, he attacks first
					$this->setPlayer(1);
					$this->session->set_userdata('alert', "No trump was found on Player 2's hand. Player 1 attacks first!");
				}elseif(!$fTrumpFound && $sTrumpFound){								// if trump is only found on player 2's hand, he attacks first
					$this->setPlayer(2);
					$this->session->set_userdata('alert', "No trump was found on Player 1's hand. Player 2 attacks first!");
				}
			}
			$this->session->set_userdata('status', 'Attack');
		}
		
		function setPlayer($player){
			$this->session->set_userdata('currentPlayer', $player);
		}
		
		function setNextPlayer($player){
			$this->session->set_userdata('currentPlayer',  5%($player+2));
		}
		
		function setTurn($stat){
			if($stat=='Defend'){
				$this->session->set_userdata('status', 'Defend');
			}elseif($stat=='Attack')
				$this->session->set_userdata('status', 'Attack');
		}
		
		function setDeck(){
			$this->session->set_userdata('deck', $this->shuffleDeck());
		}
		
		function setTrump(){
			$deck = $this->session->userdata('deck');
			$trump = array_pop($deck);
			$this->session->set_userdata('deck', $deck);
			$this->session->set_userdata('trump', $trump);
		}
		
		function setHand($player, $hand, $count=0){
			while($count<6 && count($this->session->userdata('deck'))>0){
				array_push($hand, $this->getCard());
				$count++;
			}
			if($player == 1)
				$this->session->set_userdata('firstHand', $hand);
			elseif($player == 2)
				$this->session->set_userdata('secondHand', $hand);
		}
		
		function setScore($winner){
			if($winner==1){
				$score = ($this->session->userdata('fScore')+1);
				$this->session->set_userdata('fScore', $score);
			}elseif($winner==2){
				$score = ($this->session->userdata('sScore')+1);
				$this->session->set_userdata('sScore', $score);
			}
		}
		
		function setWinner($player){
			$this->session->set_userdata('theWinner', $player);
			$this->setScore($player);
			$this->session->set_userdata('alert', 'Player '.$player.' wins!');
			
			redirect('gameover');
		}
		
		function setSession(){
		
			$session_data = array(
				'deck'					=> [],
				'currentPlayer'			=> 0,
				'status'				=> '',
				'trump'					=> [],
				'firstHand'				=> [],
				'secondHand'			=> [],
				'workSpace'				=> [],
				'data'					=> [],
				'attackCount'			=> 0,
				'option'				=> 0,
				'theWinner'				=> 0,
				'fScore'				=> 0,
				'sScore'				=> 0,
				'surrender'				=> 0,
				'fShuffle'				=> 0,
				'sShuffle'				=> 0,
				'alert'					=> '',
				'showHide'				=> ''
			);

			$this->session->set_userdata($session_data);
		}
		
		function setAction($i){
			$temp = $this->session->userdata('data');
			$status = $this->session->userdata('status');
			$player = $this->session->userdata('currentPlayer');
			$attackCount = $this->session->userdata('attackCount');
			$deckCount = count($this->session->userdata('deck'));
			$hand = [];
			
			foreach ($temp['hand'] as $t):					// Transfers the hand to temp array because old hand is full of holes
				$tempHand = array(
								'value' => $t['value'],
								'name'  => $t['name'],
								'suit'  => $t['suit'],
								'img'	=> $t['img']
							);
			array_push($hand, $tempHand);
			endforeach;
			
			$index = $i;
			
			if($status=='Attack')
				$this->attack($player, $hand, $index, $attackCount);

			elseif($status=='Defend')
				$this->defend($player, $hand, $index);
		}
//=============================================================================================================================================================
// GET FUNCTIONS
//=============================================================================================================================================================
		
		function getHand($player){
			if($player == 1){
				$array = $this->session->userdata('firstHand');
				return $array;
			} elseif($player == 2){
				$array = $this->session->userdata('secondHand');
				return $array;
			}
		}
		
		function getCard(){
			$array = $this->session->userdata('deck'); 
			$card = array_pop($array);
			$this->session->set_userdata('deck', $array); 
			return $card;
		}
		
		function getNextPlayer($player){
			return 5%($player+2);
		}
		
		function getShuffle($player){
			if($player==1)
				return $this->session->userdata('fShuffle');
			else
				return $this->session->userdata('sShuffle');
		}
		
//=============================================================================================================================================================
// ACTION FUNCTIONS
//=============================================================================================================================================================		
		
		function shuffleDeck(){
			$array = $this->durak_model->getDeck();
			shuffle($array);
			return $array;
		}
		
		function addToWorkSpace($card){
			$tableTop = $this->session->userdata('workSpace'); 
			array_push($tableTop, $card);
			$this->session->set_userdata('workSpace', $tableTop);
		}
		
		function attack($player, $hand, $index, $attackCount){
			$workSpace = $this->session->userdata('workSpace'); 
				
			if(empty($workSpace)){												// Checks if workspace is empty or not
				$this->setShuffle($player, 0);
				$this->attacker($player, $hand, $index, $attackCount);			// Adds the card to workspace and remove it from hand
			} elseif(!empty($workSpace)) {										// If not empty
				for($i=0; $i<count($workSpace); $i++){ 							// Checks each card on the workspace if attack card's value matches any of theirs
					if($hand[$index]['value'] == $workSpace[$i]['value']){		// if found
						$this->attacker($player, $hand, $index, $attackCount);
						break;											
					}elseif($hand[$index]['value'] != $workSpace[$i]['value'])
						$this->session->set_userdata('alert', "Card is not of the same value!");
					}
				}

			redirect('letsplaydurak');
		}
		
		function attacker($player, $hand, $index, $attackCount){
			$deckCount = count($this->session->userdata('deck'));
			$workSpace = $this->session->userdata('workSpace');
			
			//$oHand = $this->getHand($this->getNextPlayer($player));
			//$count = count($oHand);
			//if($attackCount<$count)

				if($attackCount<6){
					if(end($workSpace)!=$hand[$index]){
						$this->addToWorkSpace($hand[$index]);						// Adds the card to workspace
						unset($hand[$index]);										// Removes the card from hand
						
						$HandCount = count($hand);
						if($HandCount==0 && $deckCount==0)
							$this->setWinner($player);
						
						if($player == 1){											// Checks to see which hand to update
							$this->session->set_userdata('firstHand', $hand);
							if(!$this->session->userdata('surrender')){				// If opponent didn't surrender
								$this->setPlayer(2);								// Game continues
								$this->setTurn('Defend');
							}
						}elseif($player == 2){
							$this->session->set_userdata('secondHand', $hand);
							if(!$this->session->userdata('surrender')){
								$this->setPlayer(1);
								$this->setTurn('Defend');
							}
						}
						$this->session->set_userdata('alert', 'Player '.$player.' attacks!');
						$this->session->set_userdata('attackCount', ++$attackCount);
					}
				}else
					$this->session->set_userdata('alert', 'You have reached the maximum limit of attacks per turn');
		}
		
		function defend($player, $hand, $index){
			$workSpace = $this->session->userdata('workSpace');
			
			$suit = $this->session->userdata('trump')['suit'];
			$card = $hand[$index];
			
			if($card['suit']==$suit){										// Checks if defense card is trump
				if(end($workSpace)['suit']==$suit){							// Checks if attack card is suit
					if($card['value']>end($workSpace)['value'])			// If defense card value is higher than attack card's
						$this->defender($player, $hand, $index);			// this adds the card to the workspace and remove it from player's hand
					else
						$this->session->set_userdata('alert', 'Card is of lower value!');
				}else{														// Attack card is not suit
					$this->defender($player, $hand, $index);				// Add card to workspace and remove from hand
				}
			}elseif($card['suit']==end($workSpace)['suit']){				// If defense card is not trump
				if($card['value']>end($workSpace)['value']){				// Checks if defense card value is higher than attack card's
					$this->defender($player, $hand, $index);				// this adds the card to the workspace and remove it from player's hand
				}else
					$this->session->set_userdata('alert', 'Card is of lower value!');
			}else
				$this->session->set_userdata('alert', 'Card is not of the same suit!');
			
			redirect('letsplaydurak');
		}
		
		function defender($player, $hand, $index){
			$deckCount = count($this->session->userdata('deck'));
			
			$this->addToWorkSpace($hand[$index]);					// adds the card to the workspace
			unset($hand[$index]);									// Removes the card from hand
			
			$HandCount = count($hand);
			if($HandCount==0 && $deckCount==0)
				$this->setWinner($player);
			
			if($player == 1){										// Checks to see which hand to update
				$this->session->set_userdata('firstHand', $hand);
				$this->setPlayer(2);
			}elseif($player == 2){
				$this->session->set_userdata('secondHand', $hand);
				$this->setPlayer(1);
			}
			$this->setTurn('Attack');
			$this->setShuffle($player, 0);
			$this->session->set_userdata('alert', 'Player '.$player.' defended successfully!');	
		}
		
		function acceptCards($player){
			$this->session->set_userdata('option', 0);
			
			$tableTop = $this->session->userdata('workSpace');
			$fHand = $this->session->userdata('firstHand');
			$sHand = $this->session->userdata('secondHand');
			$fHandCount = count($fHand);
			$sHandCount = count($sHand);
			$count = count($tableTop);
			
			
			$i=0;
			while($i<$count){													// while workSpace still has cards
				$card = array_pop($tableTop);									// gets the card from the workSpace
				if($player==1){													// assigns whose hands to put the cards in
					array_push($fHand, $card);
				}elseif($player==2){
					array_push($sHand, $card);
				}
				$i++;
			}

			$this->session->set_userdata('workSpace', $tableTop);
			
			if($player==1){														// If player 1 accepts cards
				$this->setHand($player, $fHand, 6);								// add cards to player 1's hand
				$this->setHand(2, $sHand, $sHandCount);							// gets card from deck for player 2
			}elseif($player==2){												// If player 2 accepts cards
				$this->setHand($player, $sHand, 6);								// add cards to player 2's hands
				$this->setHand(1, $fHand, $fHandCount);							// gets card from deck for player 1
			}
			
			if($this->session->userdata('attackCount')==0){
				$this->setNextPlayer($player);
				$this->setTurn('Attack');
			}else
				$this->session->set_userdata('attackCount', 0);
			
			
			$this->session->set_userdata('alert', 'Player '.$player.' accepted the cards! You can continue attacking!');
			redirect('letsplaydurak');
		}
	
		// gives the opponent the option to attack or to accept the cards
		function endAttack($player){
			if($this->session->userdata('surrender')){						// If opponent surrenders
				$this->session->set_userdata('surrender', 0);				// resets surrender
				$this->acceptCards($this->getNextPlayer($player));			// opponent accepts the cards
			}
				
			$this->setNextPlayer($player);
			$this->setTurn('Defend');
			$this->session->set_userdata('option', 1);
			$this->session->set_userdata('attackCount', 0);
			
			
			$this->session->set_userdata('alert', 'Player '.$player.' has ended the attack! Accept the cards or attack?');
			redirect('letsplaydurak');
		}
		
		function backDown($player){
			$this->setNextPlayer($player);
			$this->setTurn('Attack');
			$this->session->set_userdata('surrender', 1);
			
			$this->session->set_userdata('alert', 'Player '.$player.' failed to defend! You can now add more cards!');
			redirect('letsplaydurak');
		}
		
		function fightBack(){
			$this->session->set_userdata('workSpace', []);
			$this->session->set_userdata('option', 0);
			
			$player = $this->session->userdata('currentPlayer');
			$hand = $this->getHand($player);
			$count = count($hand);
			
			$nextPlayer = $this->getNextPlayer($player);
			$nextHand = $this->getHand($nextPlayer);
			$nextCount = count($nextHand);
			
			$this->setTurn('Attack');
			
			if($count<6)
				$this->setHand($player, $hand, $count);
			if($nextCount<6)
				$this->setHand($nextPlayer, $nextHand, $nextCount);
			
			$this->session->set_userdata('alert', 'Player '.$player.' is now fighting back!');
			redirect('letsplaydurak');
		}
		
		function playAgain(){
			$data['fScore'] = $this->session->userdata('fScore');
			$data['sScore'] = $this->session->userdata('sScore');
			$data['theWinner'] = $this->session->userdata('theWinner');
			$data['status'] = $this->session->userdata('status');
			$data['alert'] = $this->session->userdata('alert');
			
			$this->load->view('templates/header', $data);
			$this->load->view('durak_intro', $data);
		}
	
	}
?>